import 'package:flutter/material.dart';
import 'package:syria_sports/widgets/dynamic_widget.dart';
import 'package:syria_sports/widgets/dynamic_widget/click_events.dart';

import '../utils.dart';



class DropdownButtonParser extends WidgetParser {

  @override
  Widget parse({
    required Map<String, dynamic> map,
    required BuildContext buildContext,
    UiListener? listener,
    dynamic cubit
  }) {
    List<dynamic>? items = map['items'];
    UiEvents? event = map.containsKey("event") ?UiEvents.fromJson(map['event']):null;
    Color? color = parseHexColor(map['color']);
    bool? isExpanded = map['is_expanded'];

    List<DropdownMenuItem<dynamic>> dropdownItems = [];
    for (Map<String, dynamic> item in items??[]) {
      dropdownItems.add(
        DropdownMenuItem<dynamic>(
          value: item['value'],
          child: DynamicWidgetBuilder.buildFromMap(
            item['child'],
            buildContext,
            listener,
          )??const Text('حدث خطأ ما!'),
        ),
      );
    }
    var ins = DropdownButton<dynamic>(
      value: listener?.cubit.uiData[map['key']],
      items: dropdownItems,
      dropdownColor: color,
      isExpanded: isExpanded??false,
      onChanged: (newValue){
        listener?.cubit.uiData[map['key']] =newValue;
        listener?.cubit.update();
        listener?.onMenuItemsChanged(event);
      },
    );

    return ins;
  }

  @override
  String get widgetName => "DropdownButton";

  @override
  Map<String, dynamic> export(Widget? widget, BuildContext? buildContext) {
    var realWidget = widget as DropdownButton<dynamic>;
    List<Map<String, dynamic>?> exportedItems = [];
    for (DropdownMenuItem<dynamic> item in realWidget.items as List<DropdownMenuItem<dynamic>>) {
      exportedItems.add(
        DynamicWidgetBuilder.export(
          item.child,
          buildContext,
        ),
      );
    }

    return <String, dynamic>{
      "type": widgetName,
      "value": realWidget.value,
      "items": exportedItems,
      "onChanged": realWidget.onChanged,
    };
  }

  @override
  Type get widgetType => DropdownButton<dynamic>;
}